<?php
declare (strict_types = 1);

namespace plugin\ky_black\app\admin\controller;

use plugin\ky_black\app\admin\model\BusinessType;
use support\Request;
use support\Response;
use think\facade\Db;

class BusinessTypeController extends BaseController
{
    /**
     * 获取商家类型列表
     */
    public function list(Request $request)
    {
        $params = $request->get();
        $page = (int)($params['page'] ?? 1);
        $limit = (int)($params['limit'] ?? 10);

        $query = BusinessType::query();
        
        // 关键词搜索
        if (!empty($params['keyword'])) {
            $query->where('name', 'like', "%{$params['keyword']}%")
                  ->orWhere('code', 'like', "%{$params['keyword']}%");
        }
        
        // 状态筛选
        if (isset($params['status'])) {
            $query->where('status', (int)$params['status']);
        }
        
        $total = $query->count();
        $list = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('sort', 'asc')
                      ->orderBy('id', 'asc')
                      ->get();

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 添加商家类型
     */
    public function add(Request $request)
    {
        if (!$request->isPost()) {
            return $this->error('请求方式错误');
        }

        $params = $request->post();
        
        // 验证数据
        $rules = [
            'code' => 'required|string|max:50|unique:business_type',
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
            'sort' => 'integer|min:0'
        ];
        
        $messages = [
            'code.required' => '类型编码不能为空',
            'code.max' => '类型编码最多50个字符',
            'code.unique' => '类型编码已存在',
            'name.required' => '类型名称不能为空',
            'name.max' => '类型名称最多100个字符',
            'description.max' => '描述最多255个字符',
            'sort.integer' => '排序必须为整数',
            'sort.min' => '排序不能小于0'
        ];

        $validator = validator($params, $rules, $messages);
        if (!$validator->passes()) {
            return $this->error($validator->errors()->first());
        }

        Db::beginTransaction();
        try {
            $type = new BusinessType();
            $type->fill($params);
            $type->status = 1; // 默认启用
            $type->save();
            
            Db::commit();
            return $this->success(['id' => $type->id], '添加成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑商家类型
     */
    public function edit(Request $request)
    {
        if (!$request->isPost()) {
            return $this->error('请求方式错误');
        }

        $id = $request->input('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $type = BusinessType::find($id);
        if (!$type) {
            return $this->error('商家类型不存在');
        }

        $params = $request->post();
        
        // 验证数据
        $rules = [
            'code' => 'required|string|max:50|unique:business_type,code,' . $id,
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
            'sort' => 'integer|min:0'
        ];
        
        $messages = [
            'code.required' => '类型编码不能为空',
            'code.max' => '类型编码最多50个字符',
            'code.unique' => '类型编码已存在',
            'name.required' => '类型名称不能为空',
            'name.max' => '类型名称最多100个字符',
            'description.max' => '描述最多255个字符',
            'sort.integer' => '排序必须为整数',
            'sort.min' => '排序不能小于0'
        ];

        $validator = validator($params, $rules, $messages);
        if (!$validator->passes()) {
            return $this->error($validator->errors()->first());
        }

        Db::beginTransaction();
        try {
            $type->fill($params);
            $type->save();
            
            Db::commit();
            return $this->success([], '更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 更新商家类型状态
     */
    public function status(Request $request)
    {
        if (!$request->isPost()) {
            return $this->error('请求方式错误');
        }

        $id = $request->input('id');
        $status = $request->input('status');
        
        if (!$id || !in_array($status, [0, 1])) {
            return $this->error('参数错误');
        }

        $type = BusinessType::find($id);
        if (!$type) {
            return $this->error('商家类型不存在');
        }

        Db::beginTransaction();
        try {
            $type->status = $status;
            $type->save();
            
            Db::commit();
            return $this->success([], '状态更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('状态更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取所有启用的商家类型
     */
    public function all()
    {
        $types = BusinessType::getActiveTypes();
        return $this->success($types);
    }
} 